package com.javaforever.lightwing.gui;

import java.awt.Image;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;

import javax.imageio.ImageIO;

public class Resource {
	public List<String> getResourceStr(String fileName) throws IOException {
		try (BufferedReader br = new BufferedReader(
				new InputStreamReader(this.getClass().getResourceAsStream(fileName), "UTF-8"))) {
			List<String> contents = new ArrayList<>();
			String s = "";
			while ((s = br.readLine()) != null) {
				System.out.println(s);
				contents.add(s);
			}
			return contents;
		}
	}

	public void downloadRes(String filePath, String newFileName) throws IOException {
		newFileName = newFileName.replace("//", "/");
		System.out.println("JerryDebug:" + filePath + ":" + newFileName);
		File soureFile = new File(filePath);
		File newFile = new File(newFileName);
		if (soureFile.exists()) {
			Files.copy(soureFile.toPath(), newFile.toPath());
		} else {
			try (BufferedInputStream bi = new BufferedInputStream(this.getClass().getResourceAsStream(filePath))) {
				if (bi != null) {
					try (BufferedOutputStream bo = new BufferedOutputStream(new FileOutputStream(newFile))) {
						byte[] cache = new byte[1024];
						while (bi.read(cache) != -1) {
							bo.write(cache);
						}
					}
				}
			}
		}
	}

	public Image getImagePath(String resource) {
		Image image = null;
		InputStream is = (InputStream) this.getClass().getClassLoader().getResourceAsStream(resource);
		try {
			image = ImageIO.read(is);
		} catch (IOException e) {
		}
		return image;
	}
}